package com.coollang.smartbra.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.coollang.smartbra.R;


/**
 * Created by han on 2016/10/24.
 *
 * @author han
 * @date 2016/10/24
 * @Modifier ${MODIFIER}
 * @ModifiedTime ${MODIFIEDDATE}
 * @ModifyContent${MODIFYCONTENT}
 * @since ${VERSIONNBAME}
 */

public class ErrorRateBar extends View {

    private Paint bgPaint;//背景画笔

    private Paint progressPaint;//进度画笔


    private int mWidth;//控件宽度

    private int mHeight; //控件高度

    private Bitmap bgBitmap;

    private Bitmap fgBitmap;

    private int x = 100;

    public ErrorRateBar(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ErrorRateBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ErrorRateBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    /**
     * 初始化
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        //添加背景图
        bgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_bg_error_rate);
        //添加前景图
        fgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_pro_error_rate);
        //添加标签图
        mWidth = bgBitmap.getWidth();
        mHeight = bgBitmap.getHeight();
        //设置画笔属性
        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(mWidth, mHeight);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //背景
        canvas.drawBitmap(bgBitmap, 0, 0, bgPaint);
        Bitmap bitmap = Bitmap.createBitmap(fgBitmap, 0, 0, x, mHeight);
        //前景
        canvas.drawBitmap(bitmap, 0, 0, progressPaint);
    }

    /**
     * 进度设置
     */
    public void setProgress(int progress) {
        x =  mWidth *progress/100;
        if (x < 1) {
            x = 1;
        }
        invalidate();
    }
}
